package com.local.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.local.common.util.ResultUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 对请求进行过滤
 */
//@Order(-1) //设置过滤规则执行的优先级: 方式1
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //请求参数中包含 auth，并且值是admin，则对该请求放行。否则拦截该请求
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        //2. 获取参数authorize的值
        String auth = queryParams.getFirst("auth");

        //3. 判断参数authorize的值是否是admin
        if (!("admin".equalsIgnoreCase(auth))) {
            //4. 不是，则拦截请求，并返回result结果对象
            //return setErrorResponse(exchange, chain);//先注释，对所有的后台访问放行
        }

        //5. 是，则放行
        return chain.filter(exchange);
    }


    /**
     * 对返回的结果进行封装
     * @param exchange
     * @param chain
     * @return
     */
    private Mono<Void> setErrorResponse(ServerWebExchange exchange, GatewayFilterChain chain) {
        ResultUtil result = new ResultUtil(HttpStatus.UNAUTHORIZED.value(), "您无权访问");

        ObjectMapper mapper = new ObjectMapper();
        ObjectNode resultNode = mapper.valueToTree(result);
        byte[] bytes = resultNode.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(bytes);
        exchange.getResponse().setStatusCode(HttpStatus.OK);
        return exchange.getResponse().writeWith(Flux.just(dataBuffer));

//        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//未登录
//        return exchange.getResponse().setComplete();
    }


    /**
     * 设置过滤规则执行的优先级: 方式2
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
